using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using jSLCore.Client.Presentation.Controls;

namespace jSLCore.Client.Presentation.BaseControl.Selection
{
    public class DataGridImageButtonColumn : DataGridTextColumn
    {
        public DataGridImageButtonColumn()
        {
            IsReadOnly = true;
            Width = DataGridLength.Auto;
        }

        protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue)
        {
            //do nothing
        }

        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
            throw new InvalidOperationException("DataGridGoDetailsColumn can not be not IsReadOnly and can not generate editing element");
        }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            var button = new ImageButton
            {
                Margin = new Thickness(2),
                VerticalAlignment = VerticalAlignment.Center,
                Image =  ButtonImage,
                Content =  ButtonContent,
                /*Width = 16,
                Height = 14,*/
                ImageWidth = 14,
                ImageHeight = 14,
            };
            ToolTipService.SetToolTip(button,ButtonTooltip);
            button.Click += button_Clicked;
            if (Binding != null )
            {
                button.SetBinding(ContentControl.ContentProperty, Binding);
            }
            return button;
        }

        public object ButtonTooltip { get; set; }

        public object ButtonContent { get; set; }

        public ImageSource ButtonImage { get; set; }

        private void button_Clicked(object sender, RoutedEventArgs e)
        {
            var element = (FrameworkElement)sender;
            InvokeClick(element.DataContext);
        }

        public event EventHandler<RowSelectedEventArgs> Click;

        public void InvokeClick(object data)
        {
            EventHandler<RowSelectedEventArgs> handler = Click;
            if (handler != null) handler(this, new RowSelectedEventArgs(data));
        }
    }
}